package cn.varin.mqttclientapi.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 统一响应格式处理类
 */
@ControllerAdvice
public class UnifiedResponseHandler implements ResponseBodyAdvice<Object> {

    /**
     * 统一响应格式
     */
    public static class Result<T> {
        private int code;
        private String message;
        private T data;

        public Result(int code, String message, T data) {
            this.code = code;
            this.message = message;
            this.data = data;
        }

        // 成功响应
        public static <T> Result<T> success(T data) {
            return new Result<>(200, "success", data);
        }

        // 失败响应
        public static <T> Result<T> fail(int code, String message) {
            return new Result<>(code, message, null);
        }

        // Getter方法
        public int getCode() { return code; }
        public String getMessage() { return message; }
        public T getData() { return data; }
    }

    /**
     * 全局异常处理
     */
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public Result<Object> handleException(Exception e) {
        return Result.fail(500, e.getMessage());
    }

    /**
     * 判断是否需要处理返回值
     */
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    /**
     * 返回值处理
     */
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, 
                                  MediaType selectedContentType,
                                  Class selectedConverterType,
                                  ServerHttpRequest request, 
                                  ServerHttpResponse response) {
        // 排除swagger请求路径
        if (request.getURI().getPath().contains("swagger") 
            || request.getURI().getPath().contains("api-docs")
        ||request.getURI().getPath().contains("doc.html")) {
            return body;
        }

        // 已经封装过的直接返回
        if (body instanceof Result || body instanceof ResponseEntity) {
            return body;
        }

        // String类型需要特殊处理
        if (body instanceof String) {
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                return objectMapper.writeValueAsString(Result.success(body));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        return Result.success(body);
    }
}
